package nio;

import java.io.FileOutputStream;
import java.io.Writer;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 
 *
 */
public class Socket {
	public static void main(String[] args) throws Exception {
		t3();
	}

	public static void t1() throws Exception {
		/**
		 * ServerSocketChannel只是负责监听传如的连接和创建新的SocketChannel对象，本身不传输数据 非阻塞模式
		 * 有channel一定有socket,但有socket不一定有channel
		 * 
		 */
		// 开启ServerSocketChannel
		ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
		// 如果调用serverSocket的accept方法则和普通的没什么区别
		serverSocketChannel.socket().bind(new InetSocketAddress(8989));
		// 以非阻塞模式运行
		System.out.println(serverSocketChannel.isBlocking()
				+ "====isBlocking 判断是否阻塞before");
		serverSocketChannel.configureBlocking(false);
		System.out.println(serverSocketChannel.isBlocking()
				+ "====isBlocking before");
		while (true) {
			SocketChannel scocketChannel = serverSocketChannel.accept();
			if (scocketChannel == null) {
				t2();
				// TimeUnit.SECONDS.sleep(8);
				System.out.println("没有连接");
			} else {
				System.out.println(scocketChannel.getRemoteAddress());
				System.out.println(scocketChannel.isBlocking());
			}
		}
	}

	public static void t2() throws Exception {
		SocketChannel socketChannel = SocketChannel.open();
		SocketChannel.open(new InetSocketAddress("127.0.0.1", 8989));
		socketChannel.configureBlocking(false);
		// socketChannel.connect(new InetSocketAddress("127.0.0.1", 8989));
		TimeUnit.SECONDS.sleep(2);
		System.out.println(socketChannel.isConnected() + "==isConnected");
		System.out.println(socketChannel.isOpen() + "==isOpen");
		System.out.println(socketChannel.finishConnect() + "==finishConnect");
	}

	public static void t3() throws Exception {
		/*ReadableByteChannel read = Channels.newChannel(new FileInputStream(
				"D:/a.txt"));
		Reader reader=Channels.newReader(read, StandardCharsets.UTF_8.name());*/
		WritableByteChannel write=Channels.newChannel(new FileOutputStream("D:/a.txt"));
		Writer writer=Channels.newWriter(write, StandardCharsets.UTF_8.name());
		writer.append("best");
		writer.write("goood");
		writer.write("better");
		writer.flush();
		
	}
}
